<?php
namespace Cyfy\Modules\Translations;

/**
 * Module which handles various translations.
 * If disabled or not installed, then the default value from \Cyfy\Language is used.
 *
 * @author dandelion
 * @version 0.1
 */ 
class Module extends \Cyfy\Module
{
    /**
     * Array of languages. You can get it by method getAll()
     * @var array
     */
    static private $languages = array();
    
    /**
     * Whether has the module run
     * @var bool
     */
    static private $hasRun = false;
  
    /**
     * Administration
     * @return mixed
     */
    static function administration($name = '')
    {
        if($name == 'languages')
        {
            return self :: adminLanguages();
        }
        // not found
        return array(
            "languages" => array("name" => self :: t(10), "description" => self :: t(20), "permission" => "administration"),
        );
    }
    
    /**
     * AJAX callback
     * @return mixed
     */
    static function ajax($name)
    {
        if(!\Cyfy\Cyfy ::  permission('Translations', 'administration')) return false;
        
        switch($name)
        {
            case "delete":
                \dibi :: query("DELETE FROM [:cyfy:Translations-languages] WHERE [code] = %s", $_POST["language"]);
                \Cyfy\Message :: set(self :: t(310));
                return self :: ajaxAdminLanguages();
            
            case "setDefault":
                \dibi :: query("UPDATE [:cyfy:Translations-languages] SET [default] = false");
                \dibi :: query("UPDATE [:cyfy:Translations-languages] SET [default] = true WHERE [code] = %s", $_POST["language"]);
                \Cyfy\Message :: set(self :: t(320));
                return self :: ajaxAdminLanguages();        
                
            case "getLanguages":
                return self :: ajaxAdminLanguages(); 
        }
    }
    
    /**
     * Blocks
     * @return mixed
     */     
    static function blocks($name = '')
    {
        switch($name)
        {
            case 'language-switcher':
                return self :: getLanguageSwitcher();
         
            case 'flags':
                return self :: getFlags();
            
            case '':
                return array(
                    "flags"=> self :: t(110), 
                    "language-switcher"=> self :: t(120)
                );
            default: 
                return false;
        }
    }
    
    static public function getFlag($lang, $gray = false)
    {
        $a = ($gray) ? "_" : "";
        return "<img src=\"" . \Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/Translations/flags/" . $lang . $a . ".gif") . "\" alt=\"" . self :: $languages[$lang] . "\" />";
    }
    
    
    
    /**
     * Loads language, when starting CYFY.
     * Tries POST, SESSION, parsing current query and then COOKIES.
     * If not found, redirects to default language.
     */
    static public function loadLanguage()
    {
        // get all codes
        $result = (\dibi :: query("SELECT [code] FROM [:cyfy:Translations-languages]") -> fetchAll());
        if(count($result) == 0){
            return false;
        }
        $all = array();
        foreach($result as $l)
        {
            $all[] = $l['code'];
        }
        
        // if POST language
        if($_POST['cyfy-language'])
        {
            if(in_array($_POST['cyfy-language'], $all))
            {
                \Cyfy\Language :: setActive($_POST['cyfy-language']);           
                return true;
            }
        }
        
        // if ajax OR call
        if(($_POST['ajax'] && $_POST['module']) || ($_GET['module'] && $_GET['call'] ))
        {
            // if found
            if(in_array($_SESSION['cyfy-language'], $all))
            {
                \Cyfy\Language :: setActive($_SESSION['cyfy-language']);           
                return true;
            }
            // not - load default
            \Cyfy\Language :: setActive(self :: getDefault());
            return true;
        }

        // first param
        $first = substr(\Cyfy\Cyfy ::  $query, 0, strpos(\Cyfy\Cyfy :: $query . "/", "/"));
        // language not found
        if(!$first || !in_array($first, $all))
        {
            // check in cookies
            if($_COOKIE['cyfy-lanugage'])
            {
                // if found - ok
                $lang = $_COOKIE['cyfy-lanugage'];
            }
            else
            {
                // if not found, get default
                $lang = self :: getDefault();
            }
            
            // set new lang
            \Cyfy\Language :: setActive($lang);           
            // redirect
           \Cyfy\Cyfy ::  redirectTo(\Cyfy\Cyfy :: $query);
        }
        // language found
        \Cyfy\Language :: setActive($first);           
        \Cyfy\Cyfy ::  $query = substr(\Cyfy\Cyfy ::  $query, strpos(\Cyfy\Cyfy :: $query . "/", "/") + 1);        
        setcookie('cyfy-language', $first);
         $_SESSION['cyfy-language'] = $first;
        return true;
    }
    
    /** 
     * Returns default language.
     *
     * @return string
     */
    static public function getDefault()
    {
        $code = \dibi :: query("SELECT [code] FROM [:cyfy:Translations-languages] WHERE [default] = 1 LIMIT 1") -> fetchSingle();
        return ($code) ? $code : \Cyfy\Language :: getActive();
    }
    
    /**
     * Returns all languages in an associative array, where key is the language code
     * @return array
     */
    static public function getAll()
    {
        self :: loadLanguages();
        return self :: $languages;
    }
  
    /**
     * Returns language switcher.
     * @return string HTML content
     */
    static private function getLanguageSwitcher()
    {
        
        self :: loadLanguages();
        
        $output = "<h3>" . self :: t(30)."</h3>\n";
        $output .= "<ul id=\"languageSwitcher\">\n";
        
        foreach(self :: $languages as $lg => $language)
        {
            $active = ($lg == \Cyfy\Language :: getActive()) ? "active " : "";
            $output .= "  <li class=\"{$active}\"><a title=\"{$language}\" href=\"" . \Cyfy\Cyfy ::  getPath(\Cyfy\Cyfy ::  $query, $lg) . "\">" . self :: getFlag($lg) . "<span>{$language}</span></a></li>\n";
        }
        $output .= "</ul>\n";
        return $output;
    }
    
    /**
     * Returns language switcher - flags only.
     * @return string HTML content
     */
    static private function getFlags()
    {
        self :: loadLanguages();
        \Cyfy\Cyfy ::  CSS(\Cyfy\Cyfy ::  getSourcePath(self :: getPath(). "flags.css"));
        $output .= "<ul id=\"languageFlags\" class=\"flags\">\n";
        foreach(self :: $languages as $lg => $language)
        {
            $active = ($lg == \Cyfy\Language :: getActive()) ? "active " : "";
            $output .= "  <li class=\"{$active}\"><a title=\"{$language}\" href=\"" . \Cyfy\Cyfy ::  getPath(\Cyfy\Cyfy ::  $query, $lg) . "\">" . self :: getFlag($lg, !$active) . "</a></li>\n";
        }
        $output .= "</ul>\n";
        return $output;
    }

    /**
     * Administration of languages.
     */   
    static private function adminLanguages()
    {
        $output = "<div id=\"listOfLanguages\">" . self :: ajaxAdminLanguages() . "</div>\n\n";
        
        // add language
        $output .= "<h2>". self :: t(240) . "</h2>\n";
        $form = new Forms\AddLanguage();
        $output .= $form -> show();
        return $output;
    }
    
    /**
     * Administration of languages - just a list.
     * @return string HTML.
     */   
    static private function ajaxAdminLanguages()
    {
        $table = new \Cyfy\Modules\Objects\Table();
        $table -> header(array(self :: t(210), self :: t(220), self :: t(230),self :: t(290)));
        $result = \dibi :: query("SELECT * FROM [:cyfy:Translations-languages] ORDER BY [ownName] ASC");
        foreach($result as $lang)
        {
            // if default
            if($lang["default"])
            {
                $defaultText = self :: t(250);
            }else{  
                $defaultText = "<input type=\"submit\" value=\"" . self :: t(260) . "\" onclick=\"Cyfy.ajax('Translations', 'setDefault', '#listOfLanguages', 'language={$lang['code']}');\" />";
            }

            $language = $lang["ownName"] . " (". $lang["englishName"] .")";
            $delete = "<input type=\"submit\" value=\"". self :: t(270) . "\" onclick=\"if(confirm('" . self :: t(280, array($language))."')) Cyfy.ajax('Translations', 'delete', '#listOfLanguages', 'language={$lang['code']}'); return false;\" />";
            
            $flag = self :: getFlag($lang["code"]);
            
            $table -> row(array($flag, $lang['code'], $language, $defaultText . " " .  $delete));
        }

        return $table -> show();
    }
    
    /**
     * Loads languages into class array.
     */    
    static private function loadLanguages()
    {
        if(self :: $hasRun)
        {
            return false;
        }   
        self :: $hasRun = true;

        $result = \dibi :: query("SELECT * FROM [:cyfy:Translations-languages] ORDER BY [ownName] ASC");
    
        foreach($result as $lang)
        {
            self :: $languages[$lang["code"]] = $lang["ownName"] . " (". $lang["englishName"] .")";
        }
    }
}
